/**
 * description：dll 引入配置文件
 * author：
 * */
/*
* webpack.dll打包生成两个文件：.js、.json
* 引入公共资源包：
*       html引入js文件
*       DllReferencePlugin建立js引入索引关系——在.json文件中
* */
const fs = require('fs');
const config = require("./config");
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const DllReferencePlugin = require('webpack/lib/DllReferencePlugin');

function getDllPlugin() {
    let dllPluginArr = [], dllOutputFileArr;
    try {
        dllOutputFileArr = fs.readdirSync(`${config.dllDir}`);
    } catch (err) {
        throw new Error('请先执行npm run build:dll命令');
    }
    /* 获取所有资源类型 */
    let fileNameArr = [];
    for (let i = 0;i < dllOutputFileArr.length;i++) {
        let currentFileName = dllOutputFileArr[i].replace(new RegExp(`.${config.dllJsSuffix}|.${config.dllJsonSuffix}`), '');
        !fileNameArr.includes(currentFileName) && fileNameArr.push(currentFileName);
    }
    fileNameArr.forEach(item => {
        dllPluginArr.push(new DllReferencePlugin({
            context: __dirname,
            manifest: require(`${config.dllDir}/${item}.${config.dllJsonSuffix}`)
        }));
        dllPluginArr.push(new AddAssetHtmlPlugin({
            filepath: `${config.dllDir}/${item}.${config.dllJsSuffix}`,
            outputPath: `${config.toStaticPath}/dll`, //将vue.dll.js文件引入到主文件的outputPath+此处的outputPath
            publicPath: `/${config.toStaticPath}/dll`, //html引用vue.dll.js文件路径
            includeSourcemap: false
        }));
    });
    return dllPluginArr;
}

module.exports = {
    plugins: [
        ...getDllPlugin(),
    ]
};
